package cliente;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import cliente.userCtl.Usuario;
import mensagens.EnviaDados;
import mensagens.Login;
import mensagens.Mensagem;
import mensagens.TipoMensagem;

@SuppressWarnings("serial")
public class LoginWindow extends JPanel implements ActionListener{
	
	// componentes
	private JLabel login;
	private JLabel senha;
	private JTextField username;
	private JPasswordField password;
	private JButton ok;
	private JButton sair;
	private JFrame frame;
	
	public LoginWindow(){
		super(new GridBagLayout());
		
		GridBagConstraints cons = new GridBagConstraints();
        cons.gridwidth = GridBagConstraints.REMAINDER;

        cons.fill = GridBagConstraints.HORIZONTAL;
        
        cons.insets = new Insets(2,2,2,2);

		login = new JLabel("Usuario:");
		this.add(login,cons);
		
		username = new JTextField(20);
		username.addActionListener(this);
		this.add(username,cons);
		
		senha = new JLabel("Senha:");
		this.add(senha,cons);
		
		password = new JPasswordField(20);
		password.addActionListener(this);
		this.add(password,cons);
		
		ok = new JButton("OK");
		ok.setActionCommand("login");
		ok.addActionListener(this);
		cons.fill = GridBagConstraints.NONE;
		this.add(ok, cons);
		
		sair = new JButton("Sair");
		sair.setActionCommand("sair");
		sair.addActionListener(this);
		this.add(sair,cons);
		
		
	}
	
	public void CreateAndShowGUI(){
        
		frame = new JFrame("Login");
		
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        frame.add(this);
		
        frame.setResizable(false);
        
        // Display the window.
        frame.setSize(300,200);
        frame.setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if("login".equals(e.getActionCommand())){
			
			// String usr = username.getText();
			// String pass = password.getText();
			
			Usuario user = new Usuario();
			user.setUserName(username.getText());
			// Cria um vetor de caracteres e lê a senha do usuário
			char[] passwd = password.getPassword();
			String pass = new String(passwd);
			pass = pass.trim();
			user.setPassword(pass);
			Login loginMsg = new Login(user);
			
			Mensagem msg = EnviaDados.enviarMensagem(loginMsg);
			
			if(msg.getTipo() == TipoMensagem.OK){
				MainWindow janela = new MainWindow(user);
				janela.setSize(800,600);
				janela.setVisible(true);
				
				frame.dispose();
			} else {
				JOptionPane.showMessageDialog(frame,"Usuário ou Senha inválidos", "Erro!",JOptionPane.ERROR_MESSAGE);
			}
			
		} else if("sair".equals(e.getActionCommand())){
			frame.dispose();
		}
		
	}
	
}


